import time

from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

from userManage.models import User
from .models import Template
from projectManage.models import Project
from django.core.paginator import Paginator
from app01.views import transfer_the_page_range
from django.core.paginator import PageNotAnInteger, EmptyPage


# Create your views here.
def index(request):
    projects = Project.objects.all()
    templates = Template.objects.all().order_by("-id")
    p = request.GET.get('current_page', 1)
    projects = Project.objects.all()
    users = User.objects.all()
    p = int(p)
    paginator = Paginator(templates, 10)
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'caseTemplate/index.html', locals())


def edit_template(request):
    try:
        if request.method == 'POST':
            referer = request.headers.get('Referer')
            template_name = request.POST.get('template_name')
            project_name = request.POST.get('project_name')
            remarks = request.POST.get('remarks')
            # create_time = request.POST.get('create_time')
            update_time = time.strftime("%Y-%m-%d %H:%M:%S")
            page_name = request.POST.get('page_name')
            module_name = request.POST.get('module_name')
            creator = request.POST.get('creator')
            template_id = request.POST.get('template_id')

            # if module_name:
            #     module_name_list = module_name.split(",")
            # else:
            #     module_name_list = module_name

            check_result_method = request.POST.get('check_the_result')
            template = Template.objects.filter(id=template_id)
            template.update(
                template_name=template_name, page_name=page_name, module_name=module_name,
                project_name=project_name, check_the_result=check_result_method,
                update_time=update_time, creator=creator,
                remarks=remarks
            )
            return redirect(referer)
        else:
            return HttpResponse("demo")
    except IntegrityError as error1:
        print(error1)
        return HttpResponse("模板名称重复，请修改后再次提交！")


def search_template(request):
    try:
        if request.method == 'GET':
            start_date = request.GET.get("start_date", '')
            end_date = request.GET.get("end_date", '')
            project_name = request.GET.get('project_name', '')
            project_name = project_name.strip()
            template_name = request.GET.get('template_name', '')
            template_name = template_name.strip()
            if start_date and end_date:
                search_result = Template.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                        Q(create_time__lte=end_date + " 23:59:59"),
                                                        project_name__contains=project_name,
                                                        template_name__contains=template_name).order_by('-id')
            elif start_date:
                search_result = Template.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                        project_name__contains=project_name,
                                                        template_name__contains=template_name).order_by('-id')
            elif end_date:
                search_result = Template.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                        project_name__contains=project_name,
                                                        template_name__contains=template_name).order_by('-id')
            else:
                search_result = Template.objects.filter(project_name__contains=project_name,
                                                        template_name__contains=template_name).order_by('-id')
            p = request.GET.get('current_page', 1)
            p = int(p)
            paginator = Paginator(search_result, 10)
            page_range = transfer_the_page_range(p, paginator)
            if paginator.num_pages - p > 5:
                last_page = True
            try:
                pages = paginator.page(p)
            except PageNotAnInteger:
                pages = paginator.page(1)
            except EmptyPage:
                pages = paginator.page(paginator.num_pages)
            return render(request, 'caseTemplate/search.html', locals())
    except ValidationError as error1:
        return render(request, 'app01/500_error.html', {"error_message": "年份不能超过4位数"})


def create_template(request):
    try:
        if request.method == 'POST':
            referer = request.headers.get('Referer')
            template_name = request.POST.get('template_name')
            project_name = request.POST.get('project_name')
            remarks = request.POST.get('remarks')
            create_time = request.POST.get('create_time')
            page_name = request.POST.get('page_name')
            module_name = request.POST.get('module_name')
            creator = request.POST.get('creator')

            # if module_name:
            #     module_name_list = module_name.split(",")
            # else:
            #     module_name_list = module_name

            check_result_method = request.POST.get('check_result_method')
            template = Template.objects.all()
            template.create(
                template_name=template_name, page_name=page_name, module_name=module_name,
                project_name=project_name, check_the_result=check_result_method,
                create_time=create_time, creator=creator,
                remarks=remarks
            )
            return redirect(referer)
        else:
            return HttpResponse("demo")
    except IntegrityError:
        return HttpResponse("模板名称重复，请修改后再次提交！")


def delete_template(request, template_id):
    Template.objects.get(pk=template_id).delete()
    referer = request.headers.get('Referer')
    return redirect(referer)


def getId(request):
    if request.headers.get('x-requested-with') == 'XMLHttpRequest':
        if request.method == 'GET':
            template_name = request.GET.get('template_name')
            template = Template.objects.get(template_name__exact=template_name)
            project_name = template.project_name
            page_name = template.page_name
            module_name = template.module_name
            creator = template.creator
            # return HttpResponse("test")
            response_data = {
                "project_name": project_name,
                "page_name": page_name,
                "module_name": module_name,
                "creator": creator
            }
            return JsonResponse(response_data)